package com.mnsq.common.tools.tool;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * IP工具类
 */
public class IpUtil {
    private IpUtil() {
    }

    /**
     * 获取登录用户IP地址
     *
     * @param request
     * @return String
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.indexOf("0:") != -1) {
            ip = "本地";
        }

        if (ip.length() > 15 && ip.indexOf(",") > 0) { //"***.***.***.***".length() = 15
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }

    public static long getIp2Long(String ip) {
        String[] ipAddressInArray;
        long result = 0;
        if (StringUtils.isBlank(ip)) {
            return 0;
        } else if ("本地".equals(ip)) {
            ipAddressInArray = "127.0.0.1".split("\\.");
        } else {
            ipAddressInArray = ip.split("\\.");
        }
        for (int i = 3; i >= 0; i--) {
            long ipValue = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ipValue << (i * 8);
        }
        return result;
    }

}
